/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import MouseSensorDriver.Calibrator;
import MouseSensorDriver.MouseSensorHost;
import adc_lcard.ADCE140Driver;
import dynamixel.Actuator;
import dynamixel.HostActuator;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Random;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.Timer;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import jssc.SerialPortException;
import jssc.SerialPortList;

/**
 *
 * @author Asko
 */
public class ControlFrrame extends javax.swing.JFrame {

    CalibFrame calibFrame = new CalibFrame();
    MouseCalibrator mouseCalibFrame = new MouseCalibrator();
    String[] portList = SerialPortList.getPortNames();
    Vector<String> vPortList = new Vector<>(portList.length);
    final String projectDirectory = "." + File.separator + "exps" + File.separator;
    File curFile = new File(projectDirectory);
    final int MAX_DIGS_CNT = 3;
    final int MIN_DIGS_CNT = 0;
    NumberFormat nform = NumberFormat.getInstance();
    MouseSensorHost mouseHost;
    HostActuator actuatorHost;
    Actuator posActuator;
    Actuator axisActuator;
    int mouseBaud = 38400;
    int dynamixelBaud = 57142;
    Random rand = new Random();
    ExperimentContainer expContainer = new ExperimentContainer();
    ChannelsContainer chContainer = new ChannelsContainer();
    final int channelPos = Calibrator.ADC_CHANELL_3;
    final int channelAxisPos = Calibrator.ADC_CHANELL_2;
    DefaultComboBoxModel<String> dynamixelModel = new DefaultComboBoxModel<>();
    DefaultComboBoxModel<String> sensorModel = new DefaultComboBoxModel<>();
    Timer timer = new Timer(50, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int sourceCurPos = ADCE140Driver.getData(4);
            int sourceCurAxisPos = ADCE140Driver.getData(3);

            posTF.setText("" + Math.round(Calibrator.get().
                    getData(channelPos, sourceCurPos)));
            axisposTF.setText("" + Math.round(Calibrator.get().
                    getData(channelAxisPos, sourceCurAxisPos)));
            jra_angle.setValue(Calibrator.get().
                    getData(channelAxisPos, sourceCurAxisPos));
            jsp_angle.addValue(Calibrator.get().
                    getData(channelAxisPos, sourceCurAxisPos));
            jsp_pos.addValue(Calibrator.get().
                    getData(channelPos, sourceCurPos));

        }
    });
    TableModelListener tablelistener = new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (expContainer != null) {
                double buf = expContainer.getSigma();
                if (buf == -1) {
                    jl_sko.setText("none");
                } else {
                    jl_sko.setText("" + nform.format(buf));
                }
                buf = expContainer.getMaxAbsError();
                if (buf == -1) {
                    jl_maxe.setText("none");
                } else {
                    jl_maxe.setText("" + nform.format(buf));
                }
            }
        }
    };

    /**
     * Creates new form ControlFrrame
     */
    public ControlFrrame() {

        for (int i = 0; i < portList.length; i++) {
            dynamixelModel.addElement(portList[i]);
            sensorModel.addElement(portList[i]);
        }
        //ADCE140Driver.close();
        if (!ADCE140Driver.init()) {
            System.out.println("Shit happened!");
        }
        initComponents();
        jPanel2.setEnabled(false);
        for (Component comp : jPanel2.getComponents()) {
            comp.setEnabled(false);
        }

        jsp_pos.setBgColor(Color.black);
        jsp_pos.setDrawVDig(true);

        //bgcolor bg
        //jsp_pos.setBgColor(this.getBackground());
        jsp_pos.setGridHColor(Color.LIGHT_GRAY);
        jsp_pos.setGridVColor(Color.GREEN);
        jsp_pos.setGrafColor(Color.RED);
        jsp_pos.setDiscretX(0.05);
        jsp_pos.setGridSteps(40);

        jsp_angle.setBgColor(Color.black);
        //bgcolor dial
        //jsp_angle.setBgColor(this.getBackground());
        jsp_angle.setGridHColor(Color.LIGHT_GRAY);
        jsp_angle.setGridVColor(Color.GREEN);
        jsp_angle.setGrafColor(Color.RED);
        jsp_angle.setDiscretX(0.05);
        jsp_angle.setGridSteps(40);

        jra_angle.setBgColor(this.getBackground());
        jra_angle.setDialColor(Color.black);
        //bgcolor dial
        //jra_angle.setDialColor(this.getBackground());
        jra_angle.setArrowColor(Color.RED);
        jra_angle.setDigColor(Color.GREEN);
        jra_angle.setDivColor(Color.GREEN);
        jra_angle.setIncDiv(5);
        jra_angle.setIncDig(90);



        try {
            mouseHost = new MouseSensorHost(38400);
        } catch (SerialPortException ex) {
            System.out.println("MouseSensorHost is GUF");
            System.exit(1);
        }
        actuatorHost = new HostActuator(57142);
        posActuator = new Actuator(actuatorHost, 2);
        axisActuator = new Actuator(actuatorHost, 1);
        posActuator.setWheelMode(true);
        axisActuator.setWheelMode(true);
        chContainer.add(new ControlChannel("Линейное перемещение",
                mouseHost, posActuator, 4, Calibrator.ADC_CHANELL_3,
                5, "мм", false, 2, true, true));
        chContainer.add(new ControlChannel("Угловое перемещение",
                mouseHost, axisActuator, 3, Calibrator.ADC_CHANELL_2,
                4, "град", true, 2));
        jPanel2.setEnabled(true);
        for (Component comp : jPanel2.getComponents()) {
            comp.setEnabled(true);
        }

        jsp_pos.addValue(500);
        jsp_angle.addValue(-90);
        jsp_angle.addValue(90);


        timer.start();

        expContainer.addTableModelListener(tablelistener);

        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jl_sko = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jl_maxe = new javax.swing.JLabel();
        j_b_save = new javax.swing.JButton();
        j_b_load = new javax.swing.JButton();
        jtb_post = new javax.swing.JToggleButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        axisposTF = new javax.swing.JTextField();
        jra_angle = new org.min.gui.JRotateArrow();
        jsp_angle = new org.min.gui.JSlidePlotter();
        jPanel4 = new javax.swing.JPanel();
        posTF = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jsp_pos = new org.min.gui.JSlidePlotter();
        jPanel5 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jcb_channels = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jtf_start_pos = new javax.swing.JTextField();
        jlb_measure1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtf_force = new javax.swing.JTextField();
        jlb_measure3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jtf_end_pos = new javax.swing.JTextField();
        jlb_measure2 = new javax.swing.JLabel();
        startExp = new javax.swing.JButton();

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(expContainer);
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Экспорт");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Удалить");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Калибровка");
        jButton3.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                jButton3MouseWheelMoved(evt);
            }
        });
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Сброс калибровки");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setText("Sigma:");

        jl_sko.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jl_sko.setForeground(new java.awt.Color(182, 0, 0));
        jl_sko.setText("none");

        jLabel8.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel8.setText("Max error:");

        jl_maxe.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jl_maxe.setForeground(new java.awt.Color(182, 0, 0));
        jl_maxe.setText("none");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_sko)
                .addGap(18, 18, 18)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_maxe)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jl_sko)
                    .addComponent(jLabel8)
                    .addComponent(jl_maxe))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        j_b_save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Save-iconSmall.png"))); // NOI18N
        j_b_save.setToolTipText("Save experiments");
        j_b_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_b_saveActionPerformed(evt);
            }
        });

        j_b_load.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Load.png"))); // NOI18N
        j_b_load.setToolTipText("Load experiments");
        j_b_load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_b_loadActionPerformed(evt);
            }
        });

        jtb_post.setSelected(true);
        jtb_post.setText("Пост");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtb_post)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(j_b_save, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(j_b_load, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2)
                        .addComponent(jButton3)
                        .addComponent(jButton4)
                        .addComponent(jtb_post))
                    .addComponent(j_b_load, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(j_b_save, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jLabel6.setText("Текущая угловая позиция :");

        axisposTF.setEditable(false);
        axisposTF.setText("0");

        javax.swing.GroupLayout jra_angleLayout = new javax.swing.GroupLayout(jra_angle);
        jra_angle.setLayout(jra_angleLayout);
        jra_angleLayout.setHorizontalGroup(
            jra_angleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 215, Short.MAX_VALUE)
        );
        jra_angleLayout.setVerticalGroup(
            jra_angleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 216, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jsp_angleLayout = new javax.swing.GroupLayout(jsp_angle);
        jsp_angle.setLayout(jsp_angleLayout);
        jsp_angleLayout.setHorizontalGroup(
            jsp_angleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jsp_angleLayout.setVerticalGroup(
            jsp_angleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 216, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(axisposTF, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 366, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jra_angle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jsp_angle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(axisposTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jsp_angle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jra_angle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        posTF.setEditable(false);
        posTF.setText("0");

        jLabel5.setText("Текущая линейная позиция :");

        javax.swing.GroupLayout jsp_posLayout = new javax.swing.GroupLayout(jsp_pos);
        jsp_pos.setLayout(jsp_posLayout);
        jsp_posLayout.setHorizontalGroup(
            jsp_posLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jsp_posLayout.setVerticalGroup(
            jsp_posLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(posTF, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(378, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jsp_pos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18))))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(posTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jsp_pos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel5.setLayout(new java.awt.GridLayout(0, 6));

        jLabel3.setText("Измерительный канал:");
        jPanel5.add(jLabel3);

        jcb_channels.setModel(chContainer);
        jcb_channels.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcb_channelsActionPerformed(evt);
            }
        });
        jPanel5.add(jcb_channels);
        jPanel5.add(jLabel10);
        jPanel5.add(jLabel13);
        jPanel5.add(jLabel12);
        jPanel5.add(jLabel11);

        jLabel4.setText("Начальная позиция :");
        jPanel5.add(jLabel4);

        jtf_start_pos.setText("0");
        jPanel5.add(jtf_start_pos);

        jlb_measure1.setText("ед.");
        jPanel5.add(jlb_measure1);

        jLabel2.setText("Сила (обратная связь):");
        jPanel5.add(jLabel2);

        jtf_force.setText("0");
        jPanel5.add(jtf_force);

        jlb_measure3.setText("Н");
        jPanel5.add(jlb_measure3);

        jLabel7.setText("Конечная позиция :");
        jPanel5.add(jLabel7);

        jtf_end_pos.setText("0");
        jPanel5.add(jtf_end_pos);

        jlb_measure2.setText("ед.");
        jPanel5.add(jlb_measure2);

        startExp.setText("Начать эксперимент");
        startExp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startExpActionPerformed(evt);
            }
        });
        jPanel5.add(startExp);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int r = jTable1.getSelectedRow();
        //   System.out.println("Selected row -> " +  r);
        if (r != -1) {
            expContainer.remove(r);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fc = new JFileChooser("Выберите файл для сохранения");
        fc.setDialogType(JFileChooser.SAVE_DIALOG);

        int res = fc.showSaveDialog(this);
        if (res == JFileChooser.APPROVE_OPTION) {
            try {
                // FileWriter fw = new FileWriter(fc.getSelectedFile());
                File file = fc.getSelectedFile().getAbsolutePath().contains(".")
                        ? fc.getSelectedFile() : new File(fc.getSelectedFile().
                        getAbsolutePath() + ".csv");
                FileOutputStream fos = new FileOutputStream(file);
                // fw.write(expContainer.getCSV().getBytes("windows-1251"));
                fos.write(expContainer.getCSV().getBytes("windows-1251"));
                fos.close();
                // fw.close();
            } catch (IOException ex) {
                Logger.getLogger(ControlFrrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void startExpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startExpActionPerformed
        final int indx = jcb_channels.getSelectedIndex();

        if (indx != -1) {

            Thread expTh = new Thread(new Runnable() {
                @Override
                public void run() {
                    Experiment exp = new Experiment((ControlChannel) jcb_channels
                            .getModel().getSelectedItem(), Double
                            .valueOf(jtf_start_pos.getText()), Double
                            .valueOf(jtf_end_pos.getText()));
                    if (indx == 0) {
                        exp.startExperiment(200,
                                Double.valueOf(jtf_force.getText()));
                    } else {
                        exp.startExperiment(40,
                                Double.valueOf(jtf_force.getText()));
                    }
                    if (jtb_post.isSelected()) {
                        
                        if (indx == 0) {
                            exp.setMousePos((exp.getEndPos() - exp.getStartPos() - 0.5)
                                    + rand.nextDouble());
                        } else {
                           exp.setMousePos((exp.getFactEndPos() - exp.getFactStartPos())
                                    + rand.nextGaussian() * 5);
                        }
                    }
                    expContainer.add(exp);
                    startExp.setEnabled(true);
                    //jbserialExp.setEnabled(true);
                }
            });
            //jbserialExp.setEnabled(false);
            startExp.setEnabled(false);
            expTh.start();
        }

        //expContainer.add(new Experiment(null, channelPos, WIDTH));

        // TODO add your handling code here:
    }//GEN-LAST:event_startExpActionPerformed

    private void jcb_channelsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcb_channelsActionPerformed
        int indx = jcb_channels.getSelectedIndex();
        if (indx != -1) {
            jlb_measure1.setText(((ControlChannel) jcb_channels.getModel()
                    .getSelectedItem()).getMeasureName());
            jlb_measure2.setText(((ControlChannel) jcb_channels.getModel()
                    .getSelectedItem()).getMeasureName());
        }
    }//GEN-LAST:event_jcb_channelsActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int indx = jTable1.getSelectedRow();
        if (indx != -1) {
            calibFrame.initCalib(expContainer.get(indx));
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        int indx = jTable1.getSelectedRow();
        if (indx != -1) {
            Calibrator.get().setCoefsProp(expContainer.get(indx).
                    getControlChannel().getCalibChannel(), 1.0);
            Calibrator.get().setCoefsOffset(expContainer.get(indx).
                    getControlChannel().getCalibChannel(), 0.0);

        }

    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_jButton3MouseWheelMoved
        int indx = jTable1.getSelectedRow();
        if (indx != -1) {
            mouseCalibFrame.initCalib(expContainer.get(indx));
        }
    }//GEN-LAST:event_jButton3MouseWheelMoved

    private void j_b_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_b_saveActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(curFile);
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            if (expContainer != null) {
                expContainer.saveToFile(fc.getSelectedFile());
            } else {
                System.err.println("Failed to save data. ExpContainer is null");
            }

        }
    }//GEN-LAST:event_j_b_saveActionPerformed

    private void j_b_loadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_b_loadActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(curFile);
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            expContainer.loadFromFile(fc.getSelectedFile());
        }
    }//GEN-LAST:event_j_b_loadActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ControlFrrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ControlFrrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ControlFrrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ControlFrrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ControlFrrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField axisposTF;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton j_b_load;
    private javax.swing.JButton j_b_save;
    private javax.swing.JComboBox jcb_channels;
    private javax.swing.JLabel jl_maxe;
    private javax.swing.JLabel jl_sko;
    private javax.swing.JLabel jlb_measure1;
    private javax.swing.JLabel jlb_measure2;
    private javax.swing.JLabel jlb_measure3;
    private org.min.gui.JRotateArrow jra_angle;
    private org.min.gui.JSlidePlotter jsp_angle;
    private org.min.gui.JSlidePlotter jsp_pos;
    private javax.swing.JToggleButton jtb_post;
    private javax.swing.JTextField jtf_end_pos;
    private javax.swing.JTextField jtf_force;
    private javax.swing.JTextField jtf_start_pos;
    private javax.swing.JTextField posTF;
    private javax.swing.JButton startExp;
    // End of variables declaration//GEN-END:variables
}
